package vip.liux.contracts.infrastructure.messaging.handlers;

import jakarta.mail.internet.MimeMessage;
import org.springframework.mail.javamail.JavaMailSender;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessagingException;
import vip.liux.contracts.infrastructure.messaging.MessageConst;
import vip.liux.contracts.shared.enums.messing.ChannelType;

public class EmailMessageHandler extends AbstractMessageHandler {

    private final JavaMailSender mailSender;

    EmailMessageHandler(JavaMailSender mailSender) {
        this.mailSender = mailSender;
    }

    /**
     * Handle the given message.
     *
     * @param message the message to be handled
     * @throws MessagingException if the handler failed to process the message
     */
    @Override
    public void handleMessage(Message<?> message) throws MessagingException {
        // 发送电子邮件
        String subject = "Notification";

        String title = (String) message.getHeaders().get(MessageConst.TITLE);
        if (title != null && !title.isEmpty()) {
            subject = title;
        }

        // 从消息头中提取收件人地址
        String to = (String) message.getHeaders().get(MessageConst.TO);
        if (to == null || to.isEmpty()) {
            throw new MessagingException("Missing 'to' header in the message");
        }

        // 获取消息内容
        Object payload = message.getPayload();
        if (!(payload instanceof String)) {
            throw new MessagingException("Unsupported payload type: " + payload.getClass());
        }

        try {
            MimeMessage mimeMessage = mailSender.createMimeMessage();
            mimeMessage.setFrom();
            mimeMessage.setRecipients(jakarta.mail.Message.RecipientType.TO, to);
            mimeMessage.setSubject(subject);
            mimeMessage.setText((String) payload);

            mailSender.send(mimeMessage);
        } catch (Exception e) {
            throw new MessagingException("Failed to send email to " + to, e);
        }
    }

    @Override
    public boolean supports(ChannelType channelType) {
        return ChannelType.EMAIL.equals(channelType);
    }
}